Page({
  data: {
    // 基本信息
    name: '',
    gender: '',
    contact: '',
    
    // 教育信息
    university: '',
    major: '',
    educationLevels: ['本科', '硕士', '博士', '其他'],
    educationIndex: 0,
    
    // 教学信息
    subjects: ['语文', '数学', '英语', '物理', '化学', '生物', '历史', '地理', '政治', '计算机', '艺术', '体育'],
    selectedSubjects: [], // 已选科目
    // 存储上次合法的选中状态
    lastValidSubjects: [],
    // 教学信息
    subjects: [
      {name: '语文', selected: false},
      {name: '数学', selected: false},
      {name: '英语', selected: false},
      {name: '物理', selected: false},
      {name: '化学', selected: false},
      {name: '生物', selected: false},
      {name: '历史', selected: false},
      {name: '地理', selected: false},
      {name: '政治', selected: false},
      {name: '计算机', selected: false},
      {name: '艺术', selected: false},
      {name: '体育', selected: false},
      {name: '其他', selected: false, isOther: true} // 新增 isOther 标识
    ],
    otherSubject: '', // 存储其他科目输入
    otherInputDisabled: true, // 其他科目输入框禁用状态
    
    // 时间选择
    days: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    periods: ['上午', '下午', '晚上', '全天'],
    selectedWeeks: [], // 已选星期
    timeSlots: [], // 时间段数组 [{week: '周一', period: '上午'}, ...]
    currentWeek: '', // 当前操作的星期
    selectedPeriod: '', // 当前选中的时段
    showTimeModal: false, // 时间段弹窗
    
    // 文本内容
    experience: '',
    background: '',
    personality: '',
    
    // 字数统计
    expCount: 0,
    bgCount: 0,
    personalityCount: 0
  },

  /**
   * 基本信息输入
   */
  bindNameInput(e) {
    this.setData({ name: e.detail.value });
  },
  
  bindGenderChange(e) {
    this.setData({ gender: e.detail.value });
  },
  
  bindContactInput(e) {
    this.setData({ contact: e.detail.value });
  },
  
  /**
   * 教育信息输入
   */
  bindUniversityInput(e) {
    this.setData({ university: e.detail.value });
  },
  
  bindMajorInput(e) {
    this.setData({ major: e.detail.value });
  },
  
  bindEducationChange(e) {
    this.setData({ educationIndex: e.detail.value });
  },
  
  /**
   * 科目选择
   */
  toggleSubject(e) {
    const index = e.currentTarget.dataset.index;
    const { subjects } = this.data;
    const subject = subjects[index];
    
    // 检查当前选中状态
    const currentState = subject.selected;
    
    // 计算当前已选中的科目数量
    const selectedCount = subjects.filter(item => item.selected).length;
    
    // 如果是取消选中
    if (currentState) {
      subject.selected = false;
      
      // 如果是取消选中"其他"科目，则清空输入框并禁用
      if (subject.isOther) {
        this.setData({
          subjects,
          otherSubject: '',
          otherInputDisabled: true,
          isOtherSelected: false
        });
        return;
      }
      
      this.setData({ 
        subjects,
        isOtherSelected: subjects.some(item => item.isOther && item.selected)
      });
      return;
    }
    
    // 如果是选中操作，检查是否超过限制
    if (selectedCount >= 5) {
      wx.showToast({
        title: '最多选择5个科目',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    // 更新选中状态
    subject.selected = true;
    
    // 如果是选中"其他"科目，则启用输入框
    if (subject.isOther) {
      this.setData({
        subjects,
        otherInputDisabled: false,
        isOtherSelected: true
      });
      return;
    }
    
    this.setData({ 
      subjects,
      isOtherSelected: subjects.some(item => item.isOther && item.selected)
    });
  },

  /**
 * 其他科目输入
 */
bindOtherSubjectInput(e) {
  this.setData({ otherSubject: e.detail.value });
},
  
  /**
   * 星期选择
   */
  selectWeek(e) {
    const week = e.currentTarget.dataset.week;
    const { selectedWeeks } = this.data;
    
    // 切换选中状态
    if (selectedWeeks.includes(week)) {
      // 取消选择（同时删除该日期的所有时间段）
      this.setData({
        selectedWeeks: selectedWeeks.filter(item => item !== week),
        timeSlots: this.data.timeSlots.filter(item => item.week !== week)
      });
    } else {
      // 选中星期，打开时间段选择弹窗
      this.setData({
        selectedWeeks: [...selectedWeeks, week],
        currentWeek: week,
        selectedPeriod: '',
        showTimeModal: true
      });
    }
  },
  
  /**
   * 时间段选择（支持多选）
   */
  selectPeriod(e) {
    const selectedValue = e.detail.value;
    let { selectedPeriods } = this.data;
    
    // 如果选择的是"全天"，特殊处理
    if (selectedValue === '全天') {
      // 如果已经选中全天，则取消选择
      if (selectedPeriods.includes('全天')) {
        selectedPeriods = selectedPeriods.filter(item => item !== '全天');
      } else {
        // 否则清空其他选择，只选中全天
        selectedPeriods = ['全天'];
      }
    } else {
      // 如果已经选中了全天，则先移除全天
      if (selectedPeriods.includes('全天')) {
        selectedPeriods = selectedPeriods.filter(item => item !== '全天');
      }
      
      // 处理普通选项的选中/取消
      if (selectedPeriods.includes(selectedValue)) {
        // 取消选择
        selectedPeriods = selectedPeriods.filter(item => item !== selectedValue);
      } else {
        // 添加选择
        selectedPeriods.push(selectedValue);
      }
    }
    
    this.setData({
      selectedPeriods: selectedPeriods
    });
  },
  
  // 确认时间段选择
  confirmTime() {
    if (!this.data.selectedPeriods || this.data.selectedPeriods.length === 0) {
      wx.showToast({
        title: '请选择时间段',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    const { currentWeek, selectedPeriods, timeSlots } = this.data;
    
    // 先删除该日期已有的时间段
    const newTimeSlots = timeSlots.filter(item => item.week !== currentWeek);
    
    // 处理选择的时间段
    if (selectedPeriods.includes('全天')) {
      // 全天自动拆分为三个时段，覆盖其他选择
      newTimeSlots.push(
        { week: currentWeek, period: '上午' },
        { week: currentWeek, period: '下午' },
        { week: currentWeek, period: '晚上' }
      );
    } else {
      // 添加所有选中的时间段
      selectedPeriods.forEach(period => {
        newTimeSlots.push({ week: currentWeek, period: period });
      });
    }
    
    this.setData({
      timeSlots: newTimeSlots,
      showTimeModal: false,
      // 清空选择，避免下次打开还保留之前的选择
      selectedPeriods: []
    });
  },
  
  // 关闭时间段弹窗
  closeTimeModal() {
    this.setData({ 
      showTimeModal: false,
      // 关闭时清空选择
      selectedPeriods: []
    });
  },
  
  // 删除时间段
  removeTimeSlot(e) {
    const index = e.currentTarget.dataset.index;
    const newTimeSlots = [...this.data.timeSlots];
    newTimeSlots.splice(index, 1);
    this.setData({ timeSlots: newTimeSlots });
  },

  
  /**
   * 文本输入与字数统计
   */
  bindExperienceInput(e) {
    const value = e.detail.value || '';
    this.setData({
      experience: value,
      expCount: value.length
    });
  },
  
  bindBackgroundInput(e) {
    const value = e.detail.value || '';
    this.setData({
      background: value,
      bgCount: value.length
    });
  },
  
  bindPersonalityInput(e) {
    const value = e.detail.value || '';
    this.setData({
      personality: value,
      personalityCount: value.length
    });
  },
  
  /**
   * 保存草稿
   */
  saveDraft() {
    // 从 subjects 数组中提取已选科目名称
  let selectedSubjects = this.data.subjects
  .filter(item => item.selected && !item.isOther) // 排除"其他"选项
  .map(item => item.name);

  // 如果"其他"选项被选中，添加用户输入的内容
  const otherSubject = this.data.subjects.find(item => item.isOther);
  if (otherSubject && otherSubject.selected && this.data.otherSubject.trim()) {
    selectedSubjects.push(this.data.otherSubject.trim());
  }
    
    const formData = {
      name: this.data.name,
      gender: this.data.gender,
      contact: this.data.contact,
      university: this.data.university,
      major: this.data.major,
      educationIndex: this.data.educationIndex,
      selectedSubjects: selectedSubjects, // 使用新的科目格式
      selectedWeeks: this.data.selectedWeeks,
      timeSlots: this.data.timeSlots,
      experience: this.data.experience,
      background: this.data.background,
      personality: this.data.personality,
      saveTime: new Date().toLocaleString()
    };
    
    wx.setStorageSync('tutorDraft', formData);
    
    wx.showToast({
      title: '草稿已保存',
      icon: 'success',
      duration: 2000
    });
  },
  
  /**
   * 表单提交
   */
  submitForm() {
    // 从 subjects 数组中提取已选科目名称
    let selectedSubjects = this.data.subjects
      .filter(item => item.selected && !item.isOther) // 排除"其他"选项
      .map(item => item.name);
    
    // 如果"其他"选项被选中，添加用户输入的内容
    const otherSubject = this.data.subjects.find(item => item.isOther);
    if (otherSubject && otherSubject.selected && this.data.otherSubject.trim()) {
      selectedSubjects.push(this.data.otherSubject.trim());
    }
    
    // 验证必填项
    const {
      name, gender, contact,
      university, major,
      timeSlots,
      background
    } = this.data;
    
    // 验证逻辑
    const errors = [];
    if (!name.trim()) errors.push('请填写姓名');
    if (!gender) errors.push('请选择性别');
    if (!contact.trim()) errors.push('请填写联系方式');
    if (!university.trim()) errors.push('请填写所在大学');
    if (!major.trim()) errors.push('请填写专业');
    
    // 科目验证：如果选中了"其他"但未输入内容
    if (otherSubject && otherSubject.selected && !this.data.otherSubject.trim()) {
      errors.push('请填写其他科目名称');
    }
    
    if (selectedSubjects.length === 0) {
      errors.push('请至少选择1个可授课科目');
    }
    
    if (timeSlots.length === 0) errors.push('请选择可授课时间');
    if (!background.trim()) errors.push('请填写专业优势');
    
    // 显示错误提示
    if (errors.length > 0) {
      wx.showModal({
        title: '信息不完整',
        content: errors.join('\n'),
        showCancel: false,
        confirmText: '知道了'
      });
      return;
    }
    
    // 组织提交数据
    const formData = {
      name: this.data.name,
      gender: this.data.gender,
      contact: this.data.contact,
      university: this.data.university,
      major: this.data.major,
      education: this.data.educationLevels[this.data.educationIndex],
      subjects: selectedSubjects.join(','), // 使用新的科目格式
      timeSlots: this.data.timeSlots.map(item => `${item.week}${item.period}`).join(','),
      experience: this.data.experience,
      background: this.data.background,
      personality: this.data.personality
    };
    
    // 模拟提交到服务器
    wx.showLoading({
      title: '发布中...',
      mask: true
    });

    // 发送数据到后端
    wx.request({
      url: 'http://node3-cn-hz-cu.haoyue.ltd:10086/pushIntroduction',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // form表单格式
      },
      data: formData,
      success: (res) => {
        wx.hideLoading();
        if (res.statusCode === 200) {
          wx.showToast({
            title: '发布成功',
            icon: 'success',
            duration: 2000,
            mask: true,
            success: () => {
              // 清除草稿
              wx.removeStorageSync('tutorDraft');
              // 跳转至个人中心
              setTimeout(() => {
                wx.navigateTo({
                  url: '/pages/tutor-center/tutor-center'
                });
              }, 2000);
            }
          });
        } else {
          wx.showToast({
            title: `发布失败：${res.data.message || '服务器错误'}`,
            icon: 'none',
            duration: 3000
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        wx.showToast({
          title: '网络请求失败，请重试',
          icon: 'none',
          duration: 3000
        });
        console.error('API请求失败:', err);
      }
    });
  },
  
  /**
   * 生命周期函数
   */
  onLoad() {
    // 初始化时记录合法状态
    this.lastValidSubjects = [...this.data.selectedSubjects];
    
    // 读取草稿
    const draft = wx.getStorageSync('tutorDraft');
    if (draft) {
      wx.showModal({
        title: '发现草稿',
        content: `是否加载上次保存的草稿（${draft.saveTime}）？`,
        confirmText: '加载',
        cancelText: '新建',
        success: (res) => {
          if (res.confirm) {
            // 恢复科目选中状态
            const subjects = this.data.subjects.map(item => {
              // 检查"其他"科目是否需要特殊处理
              if (item.isOther) {
                // 检查草稿中是否有"其他"科目
                const isOtherSelected = draft.selectedSubjects.some(sub => 
                  !this.data.subjects.some(s => s.name === sub && !s.isOther)
                );
                
                return {
                  ...item,
                  selected: isOtherSelected
                };
              }
              
              return {
                ...item,
                selected: draft.selectedSubjects.includes(item.name)
              };
            });
            
            // 尝试从草稿中提取"其他"科目内容
            let otherSubject = '';
            if (draft.selectedSubjects) {
              const otherSubjects = draft.selectedSubjects.filter(sub => 
                !this.data.subjects.some(s => s.name === sub && !s.isOther)
              );
              if (otherSubjects.length > 0) {
                otherSubject = otherSubjects[0];
              }
            }
            
            // 设置数据
            this.setData({
              name: draft.name,
              gender: draft.gender,
              contact: draft.contact,
              university: draft.university,
              major: draft.major,
              educationIndex: draft.educationIndex,
              subjects: subjects,
              otherSubject: otherSubject,
              otherInputDisabled: !subjects.find(item => item.isOther)?.selected,
              isOtherSelected: subjects.find(item => item.isOther)?.selected || false,
              selectedWeeks: draft.selectedWeeks,
              timeSlots: draft.timeSlots,
              experience: draft.experience,
              background: draft.background,
              personality: draft.personality,
              expCount: draft.experience ? draft.experience.length : 0,
              bgCount: draft.background ? draft.background.length : 0,
              personalityCount: draft.personality ? draft.personality.length : 0
            });
          }
        }
      });
    } else {
      // 初始化 isOtherSelected
      const isOtherSelected = this.data.subjects.find(item => item.isOther)?.selected || false;
      this.setData({ isOtherSelected });
    }
  }
})